package zhou.chs.p4_11;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import java.util.Timer;
import java.util.TimerTask;
import weiqian.hardware.HardwareControl;
import static weiqian.hardware.HardwareControl.Beep;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private boolean backlight;
    private LinearLayout layout;
    private Handler myhandler;       //信息通道
    private Timer mTimer;   //定时器
    int tn;   //定时计数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backlight = true;
        myhandler = new MyHandler();        //实例化Handler，用于进程间的通信
        layout = (LinearLayout) findViewById (R.id.activity_main);
        layout.setOnClickListener(this);    //注册屏幕单击事件
        mTimer = new Timer();         //新建Timer
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                tn++;                   //每秒加1
                Message msg1 = myhandler.obtainMessage();   //创建消息
                msg1.what = 1;                      //变量what赋值
                myhandler.sendMessage(msg1);     //发送消息
            }
        }, 1000, 1000);     //延时1000ms，然后每隔1000ms发送消息
    }
    //屏幕单击响应
    public void onClick(View view) {
        tn = 0;     //定时计数清零
        Beep();     //蜂鸣器响一声
        if(!backlight){
            backlight=true;         //如果背光关闭，打开背光
            HardwareControl.SetBackLight(backlight);
        }
    }
    //在主线程处理Handler传回来的message
    class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if(tn >= 30)
                    {
                        tn=31;  //防止tn溢出
                        backlight = false;  //超30s无屏幕单击事件，关闭背光
                        HardwareControl.SetBackLight(backlight);
                    }
                    break;
            }
        }
    }
    //程序暂停前关闭定时器，恢复常亮状态
    public void onPause() {
        super.onPause();
        HardwareControl.SetBackLight(true);
        mTimer.cancel();
    }
}
